package com.turing.model.caller.handler;

import com.turing.common.response.ResponseCode;
import com.turing.common.response.ResponseVO;
import com.turing.model.caller.client.data.DataClient;
import com.turing.model.caller.service.OcrService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Component
public class OcrCallerHandler  {

    @Resource(name = "ocrServiceImpl")
    private OcrService ocrService;

    @Resource(name = "cvOcrServiceImpl")
    private OcrService cvOcrService;

    @Autowired
    private DataClient dataClient;

    private volatile Boolean cvModelOnline;

    @XxlJob(value="callOcrJobHandler")
    public void callOCRModel(){

        List<OcrService> ocrServices = Arrays.asList(ocrService,cvOcrService);
        int nextServerIndex = getIndexByWeight();
        OcrService ocrService = ocrServices.get(nextServerIndex);
        //通过ocrService,cvOcrService去判断去执行那个实现类
        ocrService.process();

    }

    private int getIndexByWeight() {

        if(!cvModelOnline){
            return 0;
        }

        // 0.2: probability of calling curriculum vitae model
        if(Math.random() >= 0.2d){
            return 0;
        }else{
            return 1;
        }

    }

    @Scheduled(fixedDelay = 20000)
    public void updateCvModelStatus(){

        refreshCvModelStatus();

    }

    @PostConstruct
    public void init(){

        refreshCvModelStatus();

    }

    private void refreshCvModelStatus(){
        ResponseVO<Boolean> objectResponseVO = dataClient.CVOnline();
        if(objectResponseVO.getCode().equals(ResponseCode.SUCCESS)){
            this.cvModelOnline = objectResponseVO.getData();
        }
    }

}
